import time
from Simplified_code.utils.util import *
import os

if __name__ == '__main__':
    print('指纹生成完毕，接下来合并指纹文件')
    t_start = time.time()
    path = './data/waveformscegun/fp_input_cegun.json'
    dict_json = load_json_file(path)
    fname = dict_json['data']['fingerprint_files'][0]
    print(fname)
    files = dict_json['data']['fingerprint_files']

    # Stich fingerprint files
    nfp = 0
    ntimes = get_ntimes(dict_json)
    fp_in_bytes = dict_json['fingerprint']['nfreq'] * ntimes / 4
    fp_path, ts_path = get_fp_ts_folders(dict_json)
    final_fp_name = '%s%s' % (fp_path, get_combined_fp_name(dict_json))
    if os.path.exists(final_fp_name):
        os.remove(final_fp_name)
    print("Combining into final fingerprint file %s" % final_fp_name)

    final_ts_name = '%s%s' % (ts_path, get_combined_ts_name(dict_json))
    if os.path.exists(final_ts_name):
        os.remove(final_ts_name)
    print("Combining into final timestamp file %s" % final_ts_name)

    for fname in files:
        fp_file = fp_path + get_fp_fname(fname)
        os.system("cat %s >> %s" % (fp_file, final_fp_name))

        ts_file = ts_path + get_ts_fname(fname)
        os.system("cat %s >> %s" % (ts_file, final_ts_name))

        # Verify number of fingerprints
        num_lines = sum(1 for line in open(ts_file))
        nfp += num_lines
        fsize = os.path.getsize(fp_file)
        if fsize / fp_in_bytes != num_lines:
            print("Exception: # fingerprints in %s don't match" % fname)
            print("Fingerprint file: %d, timestamp file: %d" % (fsize / fp_in_bytes, num_lines))
            exit(1)

    fsize = os.path.getsize(final_fp_name)
    print("Fingerprint file size: %d bytes" % (fsize))
    print("# fingerprints: %d" % (nfp))
    ndim = fsize * 8 / nfp

    # Save fingerprint stats
    save_fp_stats(dict_json, nfp, ndim)
